package com.qbm.association.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qbm.association.bean.*;
import com.qbm.association.config.Audience;
import com.qbm.association.entity.*;
import com.qbm.association.mapper.ActivityMapper;
import com.qbm.association.mapper.ClubMapper;
import com.qbm.association.mapper.JoinActivityMapper;
import com.qbm.association.service.JoinActivityService;
import com.qbm.association.service.JoinClubService;
import com.qbm.association.service.StudentService;
import com.qbm.association.util.JWTTokenUtil;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Aron
 * @since 2022-02-07
 */
@RestController
@RequestMapping("/association/joinActivity")
public class JoinActivityController {
    @Resource
    private ActivityMapper activityMapper;

    @Resource
    private JoinActivityMapper joinActivityMapper;

    @Resource
    private JoinActivityService joinActivityService;

    @Autowired
    private Audience audience;

    @Resource
    private StudentService studentService;

    @GetMapping("getAllMyActivityByStatus")
    public ResultBean getAllMyActivityByStatus(Integer currentPage, String activityName, HttpServletRequest request) {
        QueryWrapper<JoinActivity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getId());
        queryWrapper.eq("join_activity_status", JoinActivityStatusEnum.SUCCESS.getCode());
        List<JoinActivity> joinActivityList = joinActivityService.list(queryWrapper);
        if (joinActivityList.size() == 0) {
            return ResultBean.success(new Page<>(currentPage, 5), "没有数据");
        }
        QueryWrapper<Activity> queryWrapper1 = new QueryWrapper<>();
        if (activityName != null && activityName.length() != 0) {
            queryWrapper1.like("name", activityName);
        }
        queryWrapper1.and(wrapper -> {
            for (int i = 0; i < joinActivityList.size(); i++) {
                if (i != joinActivityList.size() - 1) {
                    wrapper.eq("id", joinActivityList.get(i).getActivityId()).or();
                } else {
                    wrapper.eq("id", joinActivityList.get(i).getActivityId());
                }
            }
        });
        queryWrapper1.orderByDesc("create_time");
        Page<Activity> page = new Page<>(currentPage, 5);
        Page<Activity> page1 = activityMapper.selectPage(page, queryWrapper1);
        return ResultBean.success(page1, "获取成功");
    }

    @GetMapping("joinActivity")
    public ResultBean joinActivity(Integer clubId, Integer activityId, HttpServletRequest request) {
        // 判断人数是否到达上限，这是防止剩一个名额时两个人抢
        Activity activity = activityMapper.selectById(activityId);
        int num = joinActivityService.count(new QueryWrapper<JoinActivity>().eq("activity_id", activityId)
                .eq("join_activity_status", JoinActivityStatusEnum.SUCCESS.getCode()));
        if (!(activity.getMaxPerson() > num)) {
            return ResultBean.fail("人数已达到上限！");
        }
        JoinActivity joinActivity = new JoinActivity();
        int userId = studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getId();
        joinActivity.setUserId(userId);
        joinActivity.setClubId(clubId);
        joinActivity.setActivityId(activityId);
        joinActivity.setUserPower(JoinActivityPowerEnum.MEMBER.getCode());
        joinActivity.setJoinActivityStatus(JoinActivityStatusEnum.SUCCESS.getCode());
        boolean isTrue = joinActivityService.save(joinActivity);
        Assert.isTrue(isTrue, "加入失败");
        return ResultBean.success("加入成功");
    }

    @GetMapping("getAllApplyJoinActivityByStatus")
    public ResultBean getAllApplyJoinActivityByStatus(Integer currentPage, String activityName, HttpServletRequest request) {
        QueryWrapper<JoinActivity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getId());
        queryWrapper.eq("join_activity_status", JoinActivityStatusEnum.WAITING.getCode());
        // 排除已经提出申请或已经加入的活动
        List<JoinActivity> joinActivityList = joinActivityService.list(queryWrapper);
        if (joinActivityList.size() == 0) {
            return ResultBean.success(new Page<>(currentPage, 5), "没有数据");
        }
        QueryWrapper<Activity> queryWrapper1 = new QueryWrapper<>();
        if (activityName != null && activityName.length() != 0) {
            queryWrapper1.like("name", activityName);
        }
        queryWrapper1.and(wrapper -> {
            for (int i = 0; i < joinActivityList.size(); i++) {
                if (i != joinActivityList.size() - 1) {
                    wrapper.eq("id", joinActivityList.get(i).getActivityId()).or();
                } else {
                    wrapper.eq("id", joinActivityList.get(i).getActivityId());
                }
            }
        });
        queryWrapper1.orderByDesc("create_time");
        Page<Activity> page = new Page<>(currentPage, 5);
        Page<Activity> page1 = activityMapper.selectPage(page, queryWrapper1);
        return ResultBean.success(page1, "获取成功");
    }

    @GetMapping("getAllCanJoinActivityByStatus")
    public ResultBean getAllCanJoinActivityByStatus(Integer currentPage,String activityName, HttpServletRequest request) {
        int id = studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getId();
        Page<Student> page = new Page<>(currentPage, 5);

        IPage<List<HashMap<Object, Object>>> page1 = joinActivityMapper.getAllCanJoinActivityByStatus(
                page, activityName,id,JoinActivityStatusEnum.SUCCESS.getCode(), ActivityStatusEnum.SUCCESS.getCode());
        return ResultBean.success(page1, "获取成功");
    }
}

